﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using CommonLib;
using NetService;

namespace WordStat.Tasks
{
    internal class TaskService
    {
        internal static void InitService(string directory)
        {
            _tasksFile = Path.Combine(directory, TASK_FILE);
        }

        internal void ShowTasks()
        {
            LoadTasks();

            var wnd = new TasksWindow(this);
            wnd.ShowDialog();

            SaveTasks();
        }

        private void SaveTasks()
        {
            return;

            var serializer = new XmlSerializer(typeof(Tasks));

            using (var reader = new StreamWriter(_tasksFile))
            {
                var tasks = new Tasks { TaskList = _taskList };

                serializer.Serialize(reader, tasks);
            }
        }

        private void LoadTasks()
        {
            _taskList.Clear();

            if (!File.Exists(_tasksFile))
                return;

            var serializer = new XmlSerializer(typeof(Tasks));

            using (var reader = new StreamReader(_tasksFile))
            {
                var res = serializer.Deserialize(reader) as Tasks;

                if (res == null)
                    return;

                _taskList.AddRange(res.TaskList);
            }
        }

        private List<Task> _taskList = new List<Task>();

        internal IList<Task> TaskList
        {
            get { return _taskList.AsReadOnly(); }
        }

        private static string _tasksFile;
        private const string TASK_FILE = "tasks.xml";

        public void ShowWizard(IPlugin plugin)
        {
            try
            {
                var wnd = new TasksWindow(this, plugin);
                wnd.ShowDialog();
            }
            catch(Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.ToString());
            }
        }
    }
}
